package com.cy.factory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @Author : 残影
 * @Date: 2020-09-12 11:46
 */
public class BeanFactory {
    /**
     * 定义一个properties对象
     */
    private static Properties properties;

    /**
     * 定义一个map，用户存放我们要创建的容器。我们称之为容器。
     */
    private static Map<String, Object> beans;

    //使用静态代码块为properties赋值
    static {
        try {
            //实例化对象
            properties = new Properties();
            //获取properties文件流对象
            InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
            properties.load(in);
            //实例化容器
            beans = new HashMap<>();
            //获取配置文件的所有key
            Enumeration keys = properties.keys();
            //遍历枚举
            while (keys.hasMoreElements()) {
                //取出每个key
                String key = (String) keys.nextElement();
                try {
                    beans.put(key, Class.forName(properties.getProperty(key)).newInstance());
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            throw new ExceptionInInitializerError("初始化properties失败");
        }
    }

    /**
     * 根据bean名称获取bean对象
     *
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName) {
        Object object = null;
        try {
            object = Class.forName(properties.getProperty(beanName)).newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return object;
    }

    /**
     * 根据bean名称获取bean对象
     *
     * @param beanName
     * @return
     */
    public static Object getBeanSingleton(String beanName) {
        return beans.get(beanName);
    }
}
